package com.qupai.lib_base.utils

import android.os.Environment
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.Task
import com.blankj.utilcode.util.Utils
import com.qupai.lib_base.exfun.log
import com.tencent.mmkv.MMKV
import java.io.File

object DeletePhotoUtils {
    private const val DAY_SECONDS = (24 * 60 * 60).toLong()

    /**
     * Delete photos
     * 根据设置保留天数删除照片
     */
    fun deletePhotos() {
        FileUtils.deleteAllInDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
        val saveDays = MMKV.defaultMMKV(MMKV.MULTI_PROCESS_MODE, null).decodeInt("photoSaveDays", 3)
        LogUtils.i("照片保留天数：$saveDays")
        if (saveDays <= 0) {
            return
        }
        val parentFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + File.separator + Utils.getApp().packageName
        val files = File(parentFile).listFiles()
        if (files == null || files.isEmpty()) return
        try {
            LogUtils.i("总照片数量：${files.size}")
            val dueMillis = System.currentTimeMillis() / 1000 - saveDays * DAY_SECONDS
            log("删除 $dueMillis 之前的照片")
            for (file in files) {
                val name = if (file.name.contains("_")) {
                    file.name.split("_")[0]
                } else {
                    file.name.split(".")[0]
                }
                val l = name.toLong() / 1000
                ThreadUtils.executeBySingle(object : Task<Boolean>() {
                    override fun doInBackground(): Boolean {
                        var delete = false
                        if (l <= dueMillis) {
                            delete = file.delete()
                        }
                        return delete
                    }

                    override fun onCancel() {

                    }

                    override fun onFail(t: Throwable?) {

                    }

                    override fun onSuccess(result: Boolean?) {

                    }

                })
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}